{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "353ef6fb",
   "metadata": {},
   "source": [
    "### 使用pdfplumber库将PDF文件转换为文本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0763d4e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pdfplumber\n",
    "\n",
    "pdf_path = \"./data/10027.pdf\"        # 替换为你的PDF路径\n",
    "output_txt_path = \"./data/10027_output.txt\"    # 保存输出的文本文件\n",
    "\n",
    "with pdfplumber.open(pdf_path) as pdf, open(output_txt_path, \"w\", encoding=\"utf-8\") as out_file:\n",
    "    for i, page in enumerate(pdf.pages):\n",
    "        text = page.extract_text()\n",
    "        if text:\n",
    "            # out_file.write(f\"\\n\\n=== Page {i+1} ===\\n\\n\")\n",
    "            out_file.write(text)\n",
    "        else:\n",
    "            out_file.write(f\"\\n\\n=== Page {i+1} has no extractable text ===\\n\\n\")\n",
    "\n",
    "print(f\"文本已保存到：{output_txt_path}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8183714a",
   "metadata": {},
   "source": [
    "### 使用fitz库将PDF文件转换为文本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78684bba",
   "metadata": {},
   "outputs": [],
   "source": [
    "import fitz  # PyMuPDF\n",
    "\n",
    "def extract_text_from_pdf(pdf_path):\n",
    "    # 打开 PDF 文件\n",
    "    doc = fitz.open(pdf_path)\n",
    "    # 创建一个空的字符串，用来保存所有提取的文本\n",
    "    text = \"\"\n",
    "    \n",
    "    # 遍历 PDF 中的每一页\n",
    "    for page_num in range(len(doc)):\n",
    "        page = doc.load_page(page_num)  # 加载页面\n",
    "        text += page.get_text()  # 提取页面文本\n",
    "    \n",
    "    return text\n",
    "\n",
    "def save_text_to_file(text, file_path):\n",
    "    # 将文本保存到指定的txt文件中\n",
    "    with open(file_path, 'w', encoding='utf-8') as f:\n",
    "        f.write(text)\n",
    "\n",
    "# 使用示例\n",
    "pdf_path = \"./data/10027.pdf\"  # 替换为你的 PDF 文件路径\n",
    "txt_path = \"./data/10027.txt\"\n",
    "pdf_text = extract_text_from_pdf(pdf_path)\n",
    "# 将文本保存到 txt 文件\n",
    "save_text_to_file(pdf_text, txt_path)\n",
    "\n",
    "print(f\"PDF内容已保存到 {txt_path}\")\n",
    "# 打印提取的文本\n",
    "print(pdf_text)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
